
from django.db import connection

from utils.CacheUtils import write_to_cache, read_from_cache, checkKey
from xadmin.models import Log

__author__ = 'cwd'
__date__ = '2018/3/12 10:21'

import json
import time
import datetime

from designad.models import DesignAdList, UserAdFileLibrary, AdVariation, AdUrl, AdCreative, ad_variation_data
from utils import ConversionUtils, JsonUtils
from utils.Constants import Constants
from utils.HttpUtils import HttpUtils
from utils.TokenUtils import TokenUtils
from users.models import UserProfile, UserAcount, RechargeRecord, AdPriceRate, ExoProfile

from celery import task
from utils.InitDataUtils import InitData

# 接收上传参数
adPostOrUpdate = ''
keywordsList = ''

budget_list = [
               20000, 15000, 10000,
               5000, 2000, 1000,
               750, 500, 200,
               100, 50, 20,
               ]
maxDailyBudget = 0

categories_adult_list = [
    97, 98, 102, 104, 105, 107, 108,
    110, 115, 117, 118, 125, 126, 129,
    130, 137, 139, 142, 143, 508, 510,
    515,
]
categories_entertainment_list = [
    474, 476, 478, 490, 492, 502,
    504, 506, 511,
]
categories_streaming_list = [
    496, 498, 500, 513,
]

language_nums = 186
browers_nums = 51
oper_nums = 40
carries_nums = 586
devices_nums = 60

# 获取广告日消费数据
@task
def getAdData():
    print('获取用户广告消费数据定时任务开始。。。。。')
    url = Constants.CAMPAIGNS_GET_URL
    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            print('获取用户数据ID::'+str(userId))
            try:
                for ad in DesignAdList.objects.filter(adUser_id=userId):
                    print(ad.campaign_id)
                    status = InitData.getAdStatistics(ad.campaign_id, userId)
                    if status == 0:
                        print('429跳出日数据循环')
                        break
                    time.sleep(10)
            except Exception as e:
                print(e)
            print('获取用户广告消费数据定时任务睡眠10s')
            time.sleep(10)
    print('获取用户广告消费数据定时任务结束。。。。。')
    pass


# 获取站点数据定时任务
@task
def getSitesData():
    print('获取用户站点数据定时任务开始。。。。。')

    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            print('获取用户数据ID::'+str(userId))
            status = InitData.getSitesData(userId)
            if status == 0:
                print('429跳出站点数据循环')
                continue
            print('获取用户站点数据定时任务睡眠10s')
            time.sleep(10)
    print('获取用户站点数据定时任务结束。。。。。')
    # print(checkKey('update_sites_temp'))
    # if not checkKey('update_sites_temp'):
    #     write_to_cache('update_sites_temp', True)
    #     print(read_from_cache('update_sites_temp'))
    #     updateSitesTempData()
    # pass


# 更新站点数据临时表数据定时任务
@task
def updateSitesTempData():
    print('更新站点数据临时表数据定时任务开始。。。。。')
    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            InitData.updateSitesTempData(userId)
            print('更新站点数据临时表数据定时任务睡眠10s')
            time.sleep(10)

    print('更新站点数据临时表数据定时任务结束。。。。。')


# 获取广告时消费数据
@task
def getAdHourData():
    print('获取用户分时数据定时任务开始。。。。。')
    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            try:
                for ad in DesignAdList.objects.filter(adUser_id=userId):
                    status = InitData.getHourData(ad.campaign_id, userId)
                    if status == 0:
                        print('429跳出时数据循环')
                        break
                    time.sleep(10)
            except Exception as e:
                print(e)
        time.sleep(10)
    print('获取用户分时数据定时任务结束。。。。')

# 获取广告时消费数据
@task
def getAdVariationData():
    print('获取广告内容数据定时任务开始。。。。。')
    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            try:
                status = InitData.getAdVariation(userId)
                if status == 0:
                    print('429跳出时数据循环')
                    break
            except Exception as e:
                print(e)
        time.sleep(10)
    print('获取广告内容数据定时任务结束。。。。')

# 判断用户余额是否低于50美元
@task
def is_cost_spent():
    print('判断用户余额是否低于50美元定时任务开始。。。。。')
    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            print('获取用户数据ID::'+str(userId))
            try:
                user_account = UserAcount.objects.filter(user_id=userId)
                if user_account.count() > 0:
                    if user_account[0].balance <= 50:
                        exo_profile = ExoProfile.objects.filter(mon_user_id=userId,
                                                                is_lt_fifty=0)
                        print(exo_profile.count())
                        if exo_profile.count() > 0:
                            ads = DesignAdList.objects.filter(adUser_id=userId)
                            for ad in ads:
                                print(ad.campaign_id)
                                data = HttpUtils.putHttp(Constants.CAMPAIGNS_PAUSE_URL, {"campaign_ids": [ad.campaign_id]},
                                                         userId)
                                if data.status_code == 200:
                                    DesignAdList.objects.filter(adUser_id=userId, campaign_id=ad.campaign_id).update(status=8)
                                    AdVariation.objects.filter(user_id=userId, adCampaigns_id=ad.id).update(status=2)
                            cursor = connection.cursor()
                            cursor.execute('update users_userprofile_groups set group_id = 2 where userprofile_id = '+str(userId))
                        else:
                            ads = DesignAdList.objects.filter(adUser_id=userId)
                            for ad in ads:
                                if ad.status == 8:
                                    DesignAdList.objects.filter(adUser_id=userId, campaign_id=ad.campaign_id).update(
                                        status=0)
                                    AdVariation.objects.filter(user_id=userId, adCampaigns_id=ad.id).update(status=1)
                            if ads[0].status == 8:
                                cursor = connection.cursor()
                                cursor.execute(
                                    'update users_userprofile_groups set group_id = 1 where userprofile_id = ' + str(
                                        userId))

                    if user_account[0].balance > 50:
                        ads = DesignAdList.objects.filter(adUser_id=userId)
                        for ad in ads:
                            if ad.status == 8:
                                DesignAdList.objects.filter(adUser_id=userId, campaign_id=ad.campaign_id).update(status=0)
                                AdVariation.objects.filter(user_id=userId, adCampaigns_id=ad.id).update(status=1)
                        if ads[0].status == 8:
                            cursor = connection.cursor()
                            cursor.execute(
                                'update users_userprofile_groups set group_id = 1 where userprofile_id = ' + str(userId))

            except Exception as e:
                print(e)
        time.sleep(10)
    print('判断用户余额是否低于50美元定时任务结束。。。。。')
    pass

@task
def getCamp():
    print('同步用户广告定时任务开始。。。。。')
    InitData.getAllCamp(0)
    print('同步用户广告定时任务结束。。。。。')


@task
def getGoals():
    print('获取goal定时任务开始。。。。。')
    InitData.getGoals(0)
    print('获取goal定时任务结束。。。。。')

# 刷新Token定时任务
@task
def getToken():
    print('刷新Token定时任务开始。。。。。')
    userList = ExoProfile.objects.all()
    for user in userList:
        TokenUtils.getAPIToken(user.exo_name, user.exo_password)
    print('刷新Token定时任务结束。。。。。')
    pass


@task
def getVariStatus():
    print('获取广告材料状态定时任务开始。。。。。')
    url = Constants.CAMPAIGNS_GET_URL
    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            try:
                n = HttpUtils.getHttp(url, userId)
                if n.status_code == 200:
                    body = json.loads(n.text)
                    result = body['result']
                    for adVariStatus in result:
                        # print(adVariStatus)
                        InitData.getVariStatus(adVariStatus, userId)
            except Exception as e:
                print(e)
            time.sleep(10)
    print('获取广告材料状态定时任务结束。。。。。')


@task
def delete_variation():
    print('同步exo删除的广告材料定时任务开始。。。。。')
    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user=user.id).count() > 0:
            userId = user.id
            try:
                ad_vs = AdVariation.objects.filter(user_id=userId, status__lt=3) # ,status__lt=3

                for ad_v in ad_vs:
                    time.sleep(10)
                    ad = DesignAdList.objects.filter(
                            id=ad_v.adCampaigns_id)
                    if ad.count() > 0:
                        adVar = HttpUtils.putVariationHttp(
                            Constants.CAMPAIGNS_VARIATION_PUT_URL.format(ad[0].campaign_id,
                                 ad_v.varId),
                            json.dumps({
                                "name": ad_v.name,
                                "description": ad_v.name,
                                "url": ad_v.url,
                                "durl": ad_v.url
                            }), userId)
                        # 不存在则删除该广告内容
                        if adVar.status_code == 404:

                            print(AdVariation.objects.filter(user_id=userId, varId=ad_v.varId).update(status=3))

                            # 当url所在的广告内容所有的状态都是3时，就删除广告中的url
                            if AdVariation.objects.filter(user_id=userId, adCampaigns_id=ad_v.adCampaigns_id, url=ad_v.url, status__lt=3).count() <= 0:
                                print(AdUrl.objects.filter(adCampaigns_id=ad_v.adCampaigns_id, url=ad_v.url).delete())

                            if AdVariation.objects.filter(user_id=userId, adCampaigns_id=ad_v.adCampaigns_id, id_library_file=ad_v.id_library_file, status__lt=3).count() <= 0:
                                print(AdCreative.objects.filter(adCampaigns_id=ad_v.adCampaigns_id, id_library_file=ad_v.id_library_file).delete())
                            pass
            except Exception as e:
                print(e)

    print('同步exo删除的广告材料定时任务结束。。。。。')


@task
def getUserAcount():
    print('获取用户余额定时任务开始')

    today = datetime.date.today()
    userList = UserProfile.objects.all()
    for user in userList:
        balance = 0
        monthCost = 0
        dailyCost = 0
        pre_rate = 0
        userId = user.id
        recharge_sum = 0
        exo_recharge_sum = 0
        is_out_of = False
        balance_status = 0
        daily_cost_status = 0
        month_cost_status = 0
        newest_record = RechargeRecord.objects.filter(user_id=userId).order_by('-created_time')
        exo_profile = ExoProfile.objects.filter(mon_user_id=userId)
        try:
            if user.is_superuser != 1 and newest_record.exists() and exo_profile.count() > 0:
                rate = ConversionUtils.getRate(userId, datetime.datetime.combine(newest_record[0].created_time, datetime.time()))
                deliveryRate = rate.get('deliveryRate')
                resp = HttpUtils.getHttp(Constants.USER_ACOUNT_URL, userId)
                if resp is not None:
                    if resp.status_code == 200:
                        balance_status = 200
                        body = json.loads(resp.text)
                        result = body.get('result')
                        if type(result) is not list:
                            if result.get('balance') == 0:
                                is_out_of = True

                            # 获取最新的充值记录
                            # record = newest_record[0]
                            # 获取该用户所有的投放率
                            adPriceRate = AdPriceRate.objects.filter(user_id=userId).order_by('-created_time')

                            if adPriceRate.count() > 0:
                                # 最新的投放率
                                # newest_rate = adPriceRate[0].deliveryRate
                                if adPriceRate.count() > 1:
                                    # 获取前一次充值的投放率
                                    pre_rate = adPriceRate[1].deliveryRate

                                rate_record = RechargeRecord.objects.filter(user_id=userId, type=1, created_time__gt=str(adPriceRate[0].created_time).replace('%', ''), recharge_deliveryRate=adPriceRate[0].deliveryRate).order_by('-created_time')
                                for i in rate_record:
                                    recharge_sum += i.recharge
                                    exo_recharge_sum += i.exo_recharge

                                res_payments = HttpUtils.getHttp(Constants.USER_PAYMENTS_URL, userId)
                                if res_payments is not None:
                                    if res_payments.status_code == 200:
                                        print(res_payments.text)
                                        pay_result = json.loads(res_payments.text).get('result')
                                        wire_transfer_record = RechargeRecord.objects.filter(user_id=userId, type=0, status=0,
                                                                      created_time__gt=str(
                                                                          adPriceRate[0].created_time).replace('%',
                                                                                                               ''), )
                                        for pay_info in pay_result:
                                            if str(pay_info.get('payment_details')['payment_method']).find('Wire Transfer') == 0:
                                                if str(pay_info.get('status')['description']).find('Paid') == 0:
                                                    for wt_record in wire_transfer_record:
                                                        if str(pay_info.get('date_payment')['date']).split(' ')[0].find(str(wt_record.created_time).split(' ')[0]) == 0 \
                                                                and pay_info.get('amount')/100 == wt_record.exo_recharge:
                                                            wt_record.status = 1
                                                            wt_record.save()

                                wire_transfer = RechargeRecord.objects.filter(user_id=userId, type=0, status=1, created_time__gt=str(adPriceRate[0].created_time).replace('%', ''),)
                                for j in wire_transfer:
                                    exo_recharge_sum += j.exo_recharge

                                if result.get('balance') == 0:
                                    balance = round(0.00, 2)
                                elif pre_rate != 0 and exo_recharge_sum != 0:
                                    exo_recharge = ((float(exo_recharge_sum) + float(adPriceRate[0].recharge_balance)) / float(deliveryRate))
                                    balance = round(float(result.get('balance') / float(deliveryRate)) + float(
                                        recharge_sum) - exo_recharge + (float(adPriceRate[0].recharge_balance) / float(pre_rate)), 2)
                                elif adPriceRate.count() == 1 and exo_recharge_sum != 0:
                                    exo_recharge = (float(exo_recharge_sum) / float(deliveryRate))
                                    balance = round(float(result.get('balance') / float(deliveryRate)) + float(recharge_sum) - exo_recharge, 2)


                resp = HttpUtils.getHttp(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, today), userId)
                # print(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, today))
                if resp is not None:
                    if resp.status_code == 200:
                        daily_cost_status = 200
                        body = json.loads(resp.text)
                        result = body.get('result')

                        for costDailyData in result:
                            dailyCost = round(float(costDailyData.get('cost')) / float(deliveryRate), 2)
                            # print(dailyCost)
                            # 只获取第一个数据，就是今天的消费数据，可省略
                            break

                day_now = datetime.date.today()
                day_begin = '%d-%02d-01' % (day_now.year, day_now.month)

                year = str(exo_profile[0].updated_time).split(' ')[0].split('-')[0]
                month = str(exo_profile[0].updated_time).split(' ')[0].split('-')[1]

                if int(year) == int(day_now.year) and int(month) == int(day_now.month):
                    day_change_begin = str(exo_profile[0].updated_time).split(' ')[0]

                    resp = HttpUtils.getHttp(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_change_begin), userId)
                    print(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_change_begin))
                else:
                    resp = HttpUtils.getHttp(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_begin), userId)
                    print(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_begin))
                if resp is not None:
                    if resp.status_code == 200:
                        month_cost_status = 200
                        body = json.loads(resp.text)
                        result = body.get('result')

                        for dailyCostData in result:
                            rate = ConversionUtils.getRate(userId, datetime.datetime.strptime(dailyCostData.get('ddate'), '%Y-%m-%d'))
                            per_day_delivery_rate = rate.get('deliveryRate')
                            monthCost += round(float(dailyCostData.get('cost') / float(per_day_delivery_rate)), 2)

                            # print('{0}:::{1}'.format(round(float(dailyCostData.get('cost')), 2), monthCost))
                user_account = UserAcount.objects.filter(user_id=userId)
                if user_account.exists() and month_cost_status == 200 and balance_status == 200 and daily_cost_status == 200:
                    # 避免调整最新投放率时，但还没设置充值，而余额进行了更新
                    if user_account[0].balance == 0 and balance != 0:
                        user_account.update(
                                           balance=balance,
                                           dailyCost=dailyCost,
                                           monthCost=monthCost,
                                           )
                    elif user_account[0].balance != 0 and balance == 0 and not is_out_of:
                        user_account.update(
                                           dailyCost=dailyCost,
                                           monthCost=monthCost,
                                           )
                    elif user_account[0].balance != 0 and balance != 0:
                        user_account.update(
                                           balance=balance,
                                           dailyCost=dailyCost,
                                           monthCost=monthCost,
                                           )
                    elif user_account[0].balance == 0 and balance == 0:
                        user_account.update(
                                           balance=balance,
                                           dailyCost=dailyCost,
                                           monthCost=monthCost,
                                           )
                    elif user_account[0].balance != 0 and balance == 0 and is_out_of:
                        user_account.update(
                                           balance=balance,
                                           dailyCost=dailyCost,
                                           monthCost=monthCost,
                                           )

                elif not user_account.exists() and month_cost_status == 200 and balance_status == 200 and daily_cost_status == 200:
                    userAcount = UserAcount()
                    userAcount.user_id = userId
                    userAcount.balance = balance
                    userAcount.dailyCost = dailyCost
                    userAcount.monthCost = monthCost
                    UserAcount.save(userAcount)
        except Exception as e:
            print(e)
    print('获取用户余额定时任务结束')


# 更新某个用户的余额、消费
@task
def updateUserAcount(userId, userIsSuper):
    print('获取用户余额定时任务开始')
    today = datetime.date.today()
    balance = 0
    monthCost = 0
    dailyCost = 0
    pre_rate = 0
    recharge_sum = 0
    exo_recharge_sum = 0
    is_out_of = False
    balance_status = 0
    daily_cost_status = 0
    month_cost_status = 0
    newest_record = RechargeRecord.objects.filter(user_id=userId).order_by('-created_time')
    exo_profile = ExoProfile.objects.filter(mon_user_id=userId)
    try:
        if userIsSuper != 1 and newest_record.exists() and exo_profile.count() > 0:
            rate = ConversionUtils.getRate(userId,
                                           datetime.datetime.combine(newest_record[0].created_time, datetime.time()))
            deliveryRate = rate.get('deliveryRate')
            resp = HttpUtils.getHttp(Constants.USER_ACOUNT_URL, userId)
            if resp is not None:
                if resp.status_code == 200:
                    balance_status = 200
                    body = json.loads(resp.text)
                    result = body.get('result')
                    if type(result) is not list:
                        if result.get('balance') == 0:
                            is_out_of = True

                        # 获取最新的充值记录
                        # record = newest_record[0]
                        # 获取该用户所有的投放率
                        adPriceRate = AdPriceRate.objects.filter(user_id=userId).order_by('-created_time')

                        if adPriceRate.count() > 0:
                            # 最新的投放率
                            # newest_rate = adPriceRate[0].deliveryRate
                            if adPriceRate.count() > 1:
                                # 获取前一次充值的投放率
                                pre_rate = adPriceRate[1].deliveryRate

                            rate_record = RechargeRecord.objects.filter(user_id=userId, type=1, created_time__gt=str(
                                adPriceRate[0].created_time).replace('%', ''), recharge_deliveryRate=adPriceRate[
                                0].deliveryRate).order_by('-created_time')
                            for i in rate_record:
                                recharge_sum += i.recharge
                                exo_recharge_sum += i.exo_recharge

                            res_payments = HttpUtils.getHttp(Constants.USER_PAYMENTS_URL, userId)
                            if res_payments is not None:
                                if res_payments.status_code == 200:
                                    print(res_payments.text)
                                    pay_result = json.loads(res_payments.text).get('result')
                                    wire_transfer_record = RechargeRecord.objects.filter(user_id=userId, type=0,
                                                                                         status=0,
                                                                                         created_time__gt=str(
                                                                                             adPriceRate[
                                                                                                 0].created_time).replace(
                                                                                             '%',
                                                                                             ''), )
                                    for pay_info in pay_result:
                                        if str(pay_info.get('payment_details')['payment_method']).find(
                                                'Wire Transfer') == 0:
                                            if str(pay_info.get('status')['description']).find('Paid') == 0:
                                                for wt_record in wire_transfer_record:
                                                    if str(pay_info.get('date_payment')['date']).split(' ')[0].find(
                                                            str(wt_record.created_time).split(' ')[0]) == 0 \
                                                            and pay_info.get('amount') / 100 == wt_record.exo_recharge:
                                                        wt_record.status = 1
                                                        wt_record.save()

                            wire_transfer = RechargeRecord.objects.filter(user_id=userId, type=0, status=1,
                                                                          created_time__gt=str(
                                                                              adPriceRate[0].created_time).replace('%',
                                                                                                                   ''), )
                            for j in wire_transfer:
                                exo_recharge_sum += j.exo_recharge

                            if result.get('balance') == 0:
                                balance = round(0.00, 2)
                            elif pre_rate != 0 and exo_recharge_sum != 0:
                                exo_recharge = (
                                            (float(exo_recharge_sum) + float(adPriceRate[0].recharge_balance)) / float(
                                        deliveryRate))
                                balance = round(float(result.get('balance') / float(deliveryRate)) + float(
                                    recharge_sum) - exo_recharge + (
                                                            float(adPriceRate[0].recharge_balance) / float(pre_rate)),
                                                2)
                            elif adPriceRate.count() == 1 and exo_recharge_sum != 0:
                                exo_recharge = (float(exo_recharge_sum) / float(deliveryRate))
                                balance = round(float(result.get('balance') / float(deliveryRate)) + float(
                                    recharge_sum) - exo_recharge, 2)

            resp = HttpUtils.getHttp(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, today), userId)
            # print(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, today))
            if resp is not None:
                if resp.status_code == 200:
                    daily_cost_status = 200
                    body = json.loads(resp.text)
                    result = body.get('result')

                    for costDailyData in result:
                        dailyCost = round(float(costDailyData.get('cost')) / float(deliveryRate), 2)
                        # print(dailyCost)
                        # 只获取第一个数据，就是今天的消费数据，可省略
                        break

            day_now = datetime.date.today()
            day_begin = '%d-%02d-01' % (day_now.year, day_now.month)

            year = str(exo_profile[0].updated_time).split(' ')[0].split('-')[0]
            month = str(exo_profile[0].updated_time).split(' ')[0].split('-')[1]

            if int(year) == int(day_now.year) and int(month) == int(day_now.month):
                day_change_begin = str(exo_profile[0].updated_time).split(' ')[0]

                resp = HttpUtils.getHttp(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_change_begin),
                                         userId)
                print(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_change_begin))
            else:
                resp = HttpUtils.getHttp(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_begin), userId)
                print(Constants.STATISTICS_ADVERTISER_DATE_ACOUNT.format(today, day_begin))
            if resp is not None:
                if resp.status_code == 200:
                    month_cost_status = 200
                    body = json.loads(resp.text)
                    result = body.get('result')

                    for dailyCostData in result:
                        rate = ConversionUtils.getRate(userId, datetime.datetime.strptime(dailyCostData.get('ddate'),
                                                                                          '%Y-%m-%d'))
                        per_day_delivery_rate = rate.get('deliveryRate')
                        monthCost += round(float(dailyCostData.get('cost') / float(per_day_delivery_rate)), 2)

                        # print('{0}:::{1}'.format(round(float(dailyCostData.get('cost')), 2), monthCost))
            user_account = UserAcount.objects.filter(user_id=userId)
            if user_account.exists() and month_cost_status == 200 and balance_status == 200 and daily_cost_status == 200:
                # 避免调整最新投放率时，但还没设置充值，而余额进行了更新
                if user_account[0].balance == 0 and balance != 0:
                    user_account.update(
                        balance=balance,
                        dailyCost=dailyCost,
                        monthCost=monthCost,
                    )
                elif user_account[0].balance != 0 and balance == 0 and not is_out_of:
                    user_account.update(
                        dailyCost=dailyCost,
                        monthCost=monthCost,
                    )
                elif user_account[0].balance != 0 and balance != 0:
                    user_account.update(
                        balance=balance,
                        dailyCost=dailyCost,
                        monthCost=monthCost,
                    )
                elif user_account[0].balance == 0 and balance == 0:
                    user_account.update(
                        balance=balance,
                        dailyCost=dailyCost,
                        monthCost=monthCost,
                    )
                elif user_account[0].balance != 0 and balance == 0 and is_out_of:
                    user_account.update(
                        balance=balance,
                        dailyCost=dailyCost,
                        monthCost=monthCost,
                    )

            elif not user_account.exists() and month_cost_status == 200 and balance_status == 200 and daily_cost_status == 200:
                userAcount = UserAcount()
                userAcount.user_id = userId
                userAcount.balance = balance
                userAcount.dailyCost = dailyCost
                userAcount.monthCost = monthCost
                UserAcount.save(userAcount)
    except Exception as e:
        print(e)


    print('获取用户余额定时任务结束')


# 检查是否有广告因为网络原因或者接口问题未上传成功并上传未上传的广告
@task
def checkAdIsPost():
    print('查询广告是否上传成功并上传未上传的广告的定时任务开始')

    userList = UserProfile.objects.all()
    for user in userList:
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user_id=user.id).count() > 0:
            userId = user.id
            designList = DesignAdList.objects.filter(isPost=0, adUser_id=userId)
            if designList.count() > 0:
                for design in designList:
                    postOrUpdateAdData.delay('POST', design.id, userId, None)
        time.sleep(30)
    print('查询广告是否上传成功并上传未上传的广告的定时任务结束')


# 检查用户Token是否过期定时任务开始
@task
def checkUserToken():
    print('检查用户Token是否过期定时任务开始')
    userList = UserProfile.objects.all()
    for user in userList:
        time.sleep(10)
        if user.is_superuser != 1 and ExoProfile.objects.filter(mon_user_id=user.id).count() > 0:
            userId = user.id
            try:
                n = HttpUtils.getHttp(Constants.GOALS_URL, userId)
                print(n.status_code)
                if n.status_code == 401:
                    TokenUtils.getAPIToken(user.exo_name, user.exo_password)
            except Exception as e:
                print(e)
    print('检查用户Token是否过期定时任务结束')


# 更新广告活动的投放率
@task
def updateSitesDataRate(userId):
    print('更新广告活动的投放率定时任务开始')
    if ExoProfile.objects.filter(mon_user_id=userId).count() > 0:
        ad_list = DesignAdList.objects.filter(adUser_id=userId)
        for ad in ad_list:
            postOrUpdateAdData('PUT', ad.id, userId, eval('[{0}]'.format(ad.publisher_ad_types)))

    print('更新广告活动的投放率定时任务结束')



@task
def postOrUpdateSites(type, adId, sites, userId):
    print('上传或更新广告站点异步任务开始。。。。。')
    tarSitesList = []
    bloSitesList = []
    time.sleep(5)
    try:
        if ExoProfile.objects.filter(mon_user_id=userId).count() > 0:
            if sites is not None:
                for site in sites.split('\r\n'):
                    if site.find('-') == 0:
                        bloSitesList.append(site.replace('-', ''))
                    else:
                        tarSitesList.append(site)

            # 上传广告材料
            if type.find('POST') >= 0:
                # 上传站点
                print(json.dumps(bloSitesList))
                print(DesignAdList.objects.filter(id=adId)[0].campaign_id)
                postTarSites = HttpUtils.postSitesHttp(Constants.CAMPAIGNS_SITES_URL.format(adId, 'targeted'),
                                                       json.dumps(tarSitesList), userId
                                                       )
                postBloSites = HttpUtils.postSitesHttp(Constants.CAMPAIGNS_SITES_URL.format(adId, 'blocked'),
                                                       json.dumps(bloSitesList), userId
                                                       )
                if postTarSites is not None and postBloSites is not None:
                    print(str(postTarSites.status_code) + "  " + str(postBloSites.status_code))
                    if postTarSites.status_code == 200 or postBloSites.status_code == 200:
                        print('上传站点成功')
                    print('上传站点定位：投放：{0}  屏蔽： {1}'.format(postTarSites.text, postBloSites.text))

            # 更新广告材料
            if type.find('PUT') >= 0:
                # 更新站点
                print(json.dumps(bloSitesList))
                putTarSites = HttpUtils.putSitesHttp(Constants.CAMPAIGNS_SITES_PUT_URL.format(adId, 'targeted'),
                                                     json.dumps(tarSitesList), userId
                                                     )
                putBloSites = HttpUtils.putSitesHttp(Constants.CAMPAIGNS_SITES_PUT_URL.format(adId, 'blocked'),
                                                     json.dumps(bloSitesList), userId
                                                     )
                if postTarSites is not None and postBloSites is not None:
                    print(str(putTarSites.status_code) + "  " + str(putBloSites.status_code))
                    if putTarSites.status_code == 200 or putBloSites.status_code == 200:
                        print('更新站点成功')
                    print('更新站点定位：投放：{0}  屏蔽： {1}'.format(putTarSites.text, putBloSites.text))
    except Exception as e:
        print(e)
    print('上传或更新广告站点异步任务结束。。。。。')


# 上传数据异步任务
@task
def postOrUpdateAdData(type, adId, userId, publisher_ad_types):
    global adPostOrUpdate
    global keywordsList
    global budget_list
    global maxDailyBudget
    time.sleep(5)
    try:
        if ExoProfile.objects.filter(mon_user_id=userId).count() > 0:
            user = (UserProfile.objects.filter(id=userId))[0].username
            print('上传或更新用户{0}数据异步任务开始。。。。。'.format(user))

            ad = DesignAdList.objects.filter(id=adId)
            today = datetime.datetime.today()

            #上传广告
            tarSitesList = []
            bloSitesList = []
            cateList = []
            geoLocList = []
            langList = []
            browsersList = []
            operatingSysList = []
            moboileCarriersList = []
            devicesList = []
            monList = []
            tueList = []
            wedList = []
            thurList = []
            friList = []
            satList = []
            sunList = []
            alltimeList = []
            alltime = [
                0, 1, 2, 3, 4, 5,
                6, 7, 8, 9, 10, 11,
                12, 13, 14, 15, 16,
                17, 18, 19, 20, 21,
                22, 23
            ]
            # publisher_ad_types_list = []
            # if publisher_ad_types is None:
            #     publisher_ad_types_list.append(ad[0].publisher_ad_types)
            # else:
            #     publisher_ad_types_list = publisher_ad_types
            print(ad[0].categoriesList.count())
            if ad[0].categoriesList.count() > 0:
                for categories in ad[0].categoriesList.all():
                    # print(categories.id)
                    if categories.id == 1:
                        continue
                    if categories.id == 4:
                        continue
                    if categories.id == 5:
                        continue
                    cateList.append(categories.id)
                if set(categories_adult_list).issubset(set(cateList)):
                    cateList.append(2)
                if set(categories_entertainment_list).issubset(set(cateList)):
                    cateList.append(472)
                if set(categories_streaming_list).issubset(set(cateList)):
                    cateList.append(494)

            if ad[0].geographicLocationList.count() > 0:
                for geographicLocation in ad[0].geographicLocationList.all():
                    # print(geographicLocation.iso3)
                    geoLocList.append(geographicLocation.iso3)

            if ad[0].languagesList.count() > 0:
                for languages in ad[0].languagesList.all():
                    # print(languages.iso2)
                    langList.append(languages.id)
                if len(langList) == language_nums:
                    langList.clear()

            if ad[0].browsersList.count() > 0:
                for browser in ad[0].browsersList.all():
                    browsersList.append(browser.id)
                if len(browsersList) == browers_nums:
                    browsersList.clear()

            if ad[0].operatingSystemList.count() > 0:
                for operatingSys in ad[0].operatingSystemList.all():
                    operatingSysList.append(operatingSys.id)
                if len(operatingSysList) == oper_nums:
                    operatingSysList.clear()

            if ad[0].mobileCarriersList.count() > 0:
                for mobCarrier in ad[0].mobileCarriersList.all():
                    moboileCarriersList.append(mobCarrier.id)
                if len(moboileCarriersList) == carries_nums:
                    moboileCarriersList.clear()

            if ad[0].devicesList.count() > 0:
                for device in ad[0].devicesList.all():
                    devicesList.append(device.id)
                if len(devicesList) == devices_nums:
                    devicesList.clear()

            if ad[0].adAllTime:
                for perDate in range(1, 8):
                    timeJson = {
                        "day": perDate,
                        "hours": alltime
                    }
                    alltimeList.append(timeJson)
            else:
                for mon in ad[0].mondayList.all():
                    # print(mon.monTime.split(':')[0].strip())

                    if mon.monTime.find('0:00 - 0:00') >= 0:
                        timeJson = {
                            "day": 1,
                            "hours": alltime
                        }
                        alltimeList.append(timeJson)
                        break
                    else:
                        monList.append(mon.monTime.split(':')[0].strip())
                if len(monList) > 0:
                    timeJson = {
                        "day": 1,
                        "hours": monList
                    }
                    alltimeList.append(timeJson)
                for tue in ad[0].tuesdayList.all():
                    # print(tue.tueTime.split(':')[0].strip())
                    if tue.tueTime.find('0:00 - 0:00') >= 0:
                        timeJson = {
                            "day": 2,
                            "hours": alltime
                        }
                        alltimeList.append(timeJson)
                        break
                    else:
                        tueList.append(tue.tueTime.split(':')[0].strip())
                if len(tueList) > 0:
                    timeJson = {
                        "day": 2,
                        "hours": tueList
                    }
                    alltimeList.append(timeJson)
                for wed in ad[0].wednesdayList.all():
                    # print(wed.wedTime.split(':')[0].strip())

                    if wed.wedTime.find('0:00 - 0:00') >= 0:
                        timeJson = {
                            "day": 3,
                            "hours": alltime
                        }
                        alltimeList.append(timeJson)
                        break
                    else:
                        wedList.append(wed.wedTime.split(':')[0].strip())
                if len(wedList) > 0:
                    timeJson = {
                        "day": 3,
                        "hours": wedList
                    }
                    alltimeList.append(timeJson)
                for thur in ad[0].thursdayList.all():
                    # print(thur.thurTime.split(':')[0].strip())

                    if thur.thurTime.find('0:00 - 0:00') >= 0:
                        timeJson = {
                            "day": 4,
                            "hours": alltime
                        }
                        alltimeList.append(timeJson)
                        break
                    else:
                        thurList.append(thur.thurTime.split(':')[0].strip())
                if len(thurList) > 0:
                    timeJson = {
                        "day": 4,
                        "hours": thurList
                    }
                    alltimeList.append(timeJson)
                for fri in ad[0].fridayList.all():
                    # print(fri.friTime.split(':')[0].strip())

                    if fri.friTime.find('0:00 - 0:00') >= 0:
                        timeJson = {
                            "day": 5,
                            "hours": alltime
                        }
                        alltimeList.append(timeJson)
                        break
                    else:
                        friList.append(fri.friTime.split(':')[0].strip())
                if len(friList) > 0:
                    timeJson = {
                        "day": 5,
                        "hours": friList
                    }
                    alltimeList.append(timeJson)
                for sat in ad[0].saturdayList.all():
                    # print(sat.satTime.split(':')[0].strip())

                    if sat.satTime.find('0:00 - 0:00') >= 0:
                        timeJson = {
                            "day": 6,
                            "hours": alltime
                        }
                        alltimeList.append(timeJson)
                        break
                    else:
                        satList.append(sat.satTime.split(':')[0].strip())
                if len(satList) > 0:
                    timeJson = {
                        "day": 6,
                        "hours": satList
                    }
                    alltimeList.append(timeJson)
                for sun in ad[0].sundayList.all():
                    # print(sun.sunTime.split(':')[0].strip())

                    if sun.sunTime.find('0:00 - 0:00') >= 0:
                        timeJson = {
                            "day": 7,
                            "hours": alltime
                        }
                        alltimeList.append(timeJson)
                        break
                    else:
                        sunList.append(sun.sunTime.split(':')[0].strip())
                if len(sunList) > 0:
                    timeJson = {
                        "day": 7,
                        "hours": sunList
                    }
                    alltimeList.append(timeJson)

            if ad[0].keywords is not None:
                keywordsList = ad[0].keywords.split('\r\n')
            else:
                keywordsList = []

            if ad[0].sites is not None:
                for site in ad[0].sites.split('\r\n'):
                    if site.find('-') == 0:
                        bloSitesList.append(site.replace('-', ''))
                    else:
                        tarSitesList.append(site)

            if ad[0].isMaxDailyBudget:

                temp_budget = (float(ConversionUtils.meToExo(userId, float(ad[0].maxDailyBudget), today)))
                for temp in budget_list:
                    if temp_budget >= temp:
                        maxDailyBudget = temp * 100
                        break
            else:
                maxDailyBudget = -1

            # 新建广告
            if type.find('POST') >= 0:
                print(type)
                if int(ad[0].priceModel) == 1:
                    impressionsEnabled = False
                elif int(ad[0].priceModel) != 1 and ad[0].impressionsEnabled:
                    impressionsEnabled = True
                else:
                    impressionsEnabled = False
                adPostOrUpdate = HttpUtils.postHttp(Constants.CAMPAIGNS_URL,
                                                    getAdJson(type, ad[0].adName, ad[0].adStyle, publisher_ad_types, cateList,
                                                              geoLocList, langList, browsersList, operatingSysList,
                                                              moboileCarriersList, devicesList, int(ad[0].priceModel),
                                                              round(float(ConversionUtils.meToExo(userId, float(ad[0].price), today)) * 100, 2),
                                                              maxDailyBudget, alltimeList, keywordsList,
                                                              impressionsEnabled, ad[0].impressions,
                                                              ad[0].minutes,
                                                              ), False, userId)
                log = Log(
                    user_id=userId,
                    action_flag='post',
                    message='新建广告活动：{0}'.format(ad[0].adName)
                )
                log.save()

            # 更新广告
            if type.find('PUT') >= 0:
                print(type)
                if int(ad[0].priceModel) == 1:
                    impressionsEnabled = False
                elif int(ad[0].priceModel) != 1 and ad[0].impressionsEnabled:
                    impressionsEnabled = True
                else:
                    impressionsEnabled = False
                adPostOrUpdate = HttpUtils.putHttp(Constants.CAMPAIGNS_PUT_URL.format(ad[0].campaign_id),
                                                    getAdJson(type, ad[0].adName, ad[0].adStyle, publisher_ad_types, cateList,
                                                              geoLocList, langList, browsersList, operatingSysList,
                                                              moboileCarriersList, devicesList, int(ad[0].priceModel),
                                                              round(float(ConversionUtils.meToExo(userId, float(ad[0].price), today)) * 100, 2),
                                                              maxDailyBudget, alltimeList, keywordsList,
                                                              impressionsEnabled, ad[0].impressions,
                                                              ad[0].minutes,
                                                              ), userId)
                log = Log(
                    user_id=userId,
                    action_flag='post',
                    message='更新广告活动：{0}'.format(ad[0].adName)
                )
                log.save()
            print(adPostOrUpdate)

            if adPostOrUpdate is not None:
                if adPostOrUpdate.status_code == 400:
                    print(adPostOrUpdate.text)
                    if adPostOrUpdate.text.find('Campaign pricing minimum') >= 0:
                        ad.update(status=4)
                    elif adPostOrUpdate.text.find('Campaign pricing for CPC cannot exceed') >= 0:
                        ad.update(status=5)
                    elif adPostOrUpdate.text.find("Campaign pricing model of existing campaigns can't be changed") >= 0:
                        ad.update(status=7)
                    else:
                        ad.update(status=6)

                    return 1

                if adPostOrUpdate.status_code == 200:
                    print(adPostOrUpdate.text)
                    if adPostOrUpdate.text.find('Campaign successfully updated') < 0:
                        camp_id = adPostOrUpdate.text.split(':')[1].split('}')[0]
                    else:
                        camp_id = ad[0].campaign_id
                    # print(camp_id)
                    # 获取广告状态
                    if camp_id != 1:
                        res = HttpUtils.getHttp(Constants.CAMPAIGNS_PUT_URL.format(camp_id), userId)
                        if res is not None:
                            if res.status_code == 200:
                                body = json.loads(res.text)
                                res_status = body['result']

                        # 4是出价过低，5是CPC出价过高
                        if ad[0].status != 4 and ad[0].status != 5 and ad[0].status != 6 and ad[0].status != 7 and type.find('POST') >= 0:
                            ad.update(campaign_id=camp_id, status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])

                        elif ad[0].status == 4 and type.find('POST') >= 0:
                            ad.update(campaign_id=camp_id, status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])
                        elif ad[0].status == 4 and type.find('PUT') >= 0:
                            ad.update(status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])

                        elif ad[0].status == 6 and type.find('POST') >= 0:
                            ad.update(campaign_id=camp_id, status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])
                        elif ad[0].status == 6 and type.find('PUT') >= 0:
                            ad.update(status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])

                        elif ad[0].status == 5 and type.find('POST') >= 0:
                            ad.update(campaign_id=camp_id, status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])
                        elif ad[0].status == 5 and type.find('PUT') >= 0:
                            ad.update(status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])

                        elif ad[0].status == 7 and type.find('POST') >= 0:
                            ad.update(campaign_id=camp_id, status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])
                        elif ad[0].status == 7 and type.find('PUT') >= 0:
                            ad.update(status=res_status['campaign']['status'], checked=res_status['campaign']['checked'])


                        # 更新浏览器、操作系统、移动运营商、设备等是否选所有
                        if type.find('PUT') >= 0:
                            if len(langList) == 0:
                                lan = HttpUtils.deleteHttp(Constants.LANGUAGES_DELETE_URL.format(camp_id), userId)
                                print('广告的语言选择所有操作：{0}：{1}'.format(lan.status_code, lan.text))
                            if len(browsersList) == 0:
                                bro = HttpUtils.deleteHttp(Constants.BROWSERS_DELETE_URL.format(camp_id), userId)
                                print('广告的浏览器选择所有操作：{0}：{1}'.format(bro.status_code, bro.text))
                            if len(operatingSysList) == 0:
                                oper = HttpUtils.deleteHttp(Constants.OPERATINGS_SYSTEM_DELETE_URL.format(camp_id), userId)
                                print('广告的操作系统选择所有操作：{0}：{1}'.format(oper.status_code, oper.text))
                            if len(moboileCarriersList) == 0:
                                carrier = HttpUtils.deleteHttp(Constants.CARRIERS_DELETE_URL.format(camp_id), userId)
                                print('广告的移动运营商选择所有操作：{0}：{1}'.format(carrier.status_code, carrier.text))
                            if len(devicesList) == 0:
                                dev = HttpUtils.deleteHttp(Constants.DEVICES_DELETE_URL.format(camp_id), userId)
                                print('广告的设备选择所有操作：{0}：{1}'.format(dev.status_code, dev.text))

                        # urlCount = AdUrl.objects.filter(adCampaigns_id=designad.id).count()
                        # 上传广告材料
                        if type.find('POST') >= 0:
                            # 上传站点
                            print(json.dumps(bloSitesList))
                            postTarSites = HttpUtils.postSitesHttp(
                                Constants.CAMPAIGNS_SITES_URL.format(camp_id, 'targeted'),
                                json.dumps(tarSitesList), userId
                                )
                            postBloSites = HttpUtils.postSitesHttp(
                                Constants.CAMPAIGNS_SITES_URL.format(camp_id, 'blocked'),
                                json.dumps(bloSitesList), userId
                                )
                            print(str(postTarSites.status_code) + "  " + str(postBloSites.status_code))
                            if postTarSites.status_code == 400 or postBloSites.status_code == 400:
                                if postTarSites.text.find("Maximum number of 1500") >= 0 \
                                        or postBloSites.text.find("Maximum number of 1500") >= 0:
                                    ad.update(status=9)
                            print('上传站点定位：投放：{0}  屏蔽： {1}'.format(postTarSites.text, postBloSites.text))

                            if str(ad[0].adStyle).find('Tab - Direct Link') < 0 and str(ad[0].adStyle).find(
                                    'Popunders') < 0:
                                # 需判断状态，待优化
                                for adUrl in AdUrl.objects.filter(adCampaigns_id=adId):
                                    for adCreative in AdCreative.objects.filter(adCampaigns_id=adId):
                                        fileName = UserAdFileLibrary.objects.filter(
                                            file_id=adCreative.id_library_file)[0].file_name
                                        print('fimeName:::' + fileName)

                                        file_id = adCreative.id_library_file

                                        adVar = HttpUtils.postVariationHttp(
                                            Constants.CAMPAIGNS_VARIATION_URL.format(camp_id),
                                            getVariation(file_id, fileName,
                                                         fileName, adUrl.url), userId
                                        )

                                        print(adVar)
                                        AdVariation.objects.create(
                                            id_library_file=file_id,
                                            adCampaigns_id=adId,
                                            varId=adVar.text.split(':')[1].split('}')[0],
                                            name=fileName,
                                            description=fileName,
                                            url=adUrl.url,
                                            user_id=userId,
                                            url_id=adUrl.id,
                                            creative_id=adCreative.id,
                                            vari_url=UserAdFileLibrary.objects.filter(file_id=file_id)[0].adMaterial
                                        )

                                        print('创建多个创意匹配一个url的广告材料：{0}'.format(
                                            str(adVar.text.split(':')[1].split('}')[0])))
                            else:
                                # 需判断状态，待优化
                                for adUrl in AdUrl.objects.filter(adCampaigns_id=adId):
                                    adVar = HttpUtils.postVariationHttp(
                                        Constants.CAMPAIGNS_VARIATION_URL.format(camp_id),
                                        get_variation_without_pic(adUrl.url), userId
                                    )

                                    print(adVar)
                                    AdVariation.objects.create(
                                        adCampaigns_id=adId,
                                        varId=adVar.text.split(':')[1].split('}')[0],
                                        url=adUrl.url,
                                        user_id=userId,
                                        url_id=adUrl.id,
                                    )
                                    print('创建多个创意匹配一个url的广告材料：{0}'.format(
                                        str(adVar.text.split(':')[1].split('}')[0])))

                        # 更新广告材料
                        if type.find('PUT') >= 0:
                            # 更新站点
                            print(json.dumps(bloSitesList))
                            putTarSites = HttpUtils.putSitesHttp(
                                Constants.CAMPAIGNS_SITES_PUT_URL.format(camp_id, 'targeted'),
                                json.dumps(tarSitesList), userId
                                )
                            putBloSites = HttpUtils.putSitesHttp(
                                Constants.CAMPAIGNS_SITES_PUT_URL.format(camp_id, 'blocked'),
                                json.dumps(bloSitesList), userId
                                )
                            print(str(putTarSites.status_code) + "  " + str(putBloSites.status_code))
                            if putTarSites.status_code == 400 or putBloSites.status_code == 400:
                                if putTarSites.text.find("Maximum number of 1500") >= 0 \
                                        or putBloSites.text.find("Maximum number of 1500") >= 0:
                                    ad.update(status=9)
                            print('更新站点定位：投放：{0}  屏蔽： {1}'.format(putTarSites.text, putBloSites.text))

                            if str(ad[0].adStyle).find('Tab - Direct Link') < 0 and str(ad[0].adStyle).find('Popunders') < 0:
                                # 需判断状态，待优化
                                for adUrl in AdUrl.objects.filter(adCampaigns_id=adId):
                                    for adCreative in AdCreative.objects.filter(adCampaigns_id=adId):
                                        user_file = UserAdFileLibrary.objects.filter(
                                            file_id=adCreative.id_library_file)
                                        if user_file.count() > 0:
                                            fileName = user_file[0].file_name
                                            print('fimeName:::' + fileName)

                                            file_id = adCreative.id_library_file
                                            ad_var = AdVariation.objects.filter(adCampaigns_id=adId, url_id=adUrl.id, creative_id=adCreative.id)
                                            if ad_var.count() > 0:
                                                adVar = HttpUtils.putVariationHttp(
                                                    Constants.CAMPAIGNS_VARIATION_PUT_URL.format(camp_id, ad_var[0].varId),
                                                    json.dumps({
                                                        "name": fileName,
                                                        "description": fileName,
                                                        "url": adUrl.url,
                                                        "durl": adUrl.url
                                                    }), userId)

                                                AdVariation.objects.filter(adCampaigns_id=adId,
                                                                           varId=ad_var[0].varId).update(url=adUrl.url)
                                                if adVar.status_code == 200:
                                                    print('更新多个url匹配一个创意的广告材料：{0}'.format(
                                                        adVar.text.split(':')[1].split('}')[0]))
                                                else:
                                                    print('更新多个url匹配一个创意的广告材料失败')

                                            # 新增的
                                            else:
                                                adVar = HttpUtils.postVariationHttp(
                                                    Constants.CAMPAIGNS_VARIATION_URL.format(camp_id),
                                                    getVariation(file_id, fileName,
                                                                 fileName, adUrl.url), userId
                                                )

                                                print(adVar)
                                                AdVariation.objects.create(
                                                    id_library_file=file_id,
                                                    adCampaigns_id=adId,
                                                    varId=adVar.text.split(':')[1].split('}')[0],
                                                    name=fileName,
                                                    description=fileName,
                                                    url=adUrl.url,
                                                    user_id=userId,
                                                    url_id=adUrl.id,
                                                    creative_id=adCreative.id,
                                                    vari_url=UserAdFileLibrary.objects.filter(file_id=file_id)[0].adMaterial
                                                )
                                                print('创建多个创意匹配一个url的广告材料：{0}'.format(
                                                    str(adVar.text.split(':')[1].split('}')[0])))
                            else:
                                # 需判断状态，待优化
                                for adUrl in AdUrl.objects.filter(adCampaigns_id=adId):
                                        ad_var = AdVariation.objects.filter(adCampaigns_id=adId, url_id=adUrl.id)
                                        if ad_var.count() > 0:
                                            adVar = HttpUtils.putVariationHttp(
                                                Constants.CAMPAIGNS_VARIATION_PUT_URL.format(camp_id, ad_var[0].varId),
                                                json.dumps({
                                                    "url": adUrl.url,
                                                    "durl": adUrl.url
                                                }), userId)

                                            AdVariation.objects.filter(adCampaigns_id=adId,
                                                                       varId=ad_var[0].varId).update(url=adUrl.url)
                                            if adVar.status_code == 200:
                                                print('更新多个url匹配一个创意的广告材料：{0}'.format(
                                                    adVar.text.split(':')[1].split('}')[0]))
                                            else:
                                                print('更新多个url匹配一个创意的广告材料失败')

                                        # 新增的
                                        else:
                                            adVar = HttpUtils.postVariationHttp(
                                                Constants.CAMPAIGNS_VARIATION_URL.format(camp_id),
                                                get_variation_without_pic(adUrl.url), userId
                                            )

                                            print(adVar)
                                            AdVariation.objects.create(
                                                adCampaigns_id=adId,
                                                varId=adVar.text.split(':')[1].split('}')[0],
                                                url=adUrl.url,
                                                user_id=userId,
                                                url_id=adUrl.id,
                                                )
                                            print('创建多个创意匹配一个url的广告材料：{0}'.format(
                                                str(adVar.text.split(':')[1].split('}')[0])))

                        # 保存或更新新的字段
                        ad.update(isPost=1)

                elif adPostOrUpdate.status_code == 500:
                    print(adPostOrUpdate.text)

    except Exception as e:
        print(e)
    print('上传或更新用户{0}数据异步任务结束。。。。。'.format(user))


# 生成上传数据的json格式
def getAdJson(type, adName, adStyle, publisher_ad_types, cateList, geoLocList, langList,
              browsersList,operatingSysList, moboileCarriersList,
              devicesList, priceModel, price, maxDailyBudget, alltimeList,
              keywordsList, impressionsEnabled, impressions, minutes,
              ):
    adJson = {}
    # adTye = AdvertiserAdType.objects.filter(name=adStyle)[0]
    # 上传广告材料
    if type.find('POST') >= 0:
        adJson = JsonUtils.getPostJson(adName, adStyle, publisher_ad_types, cateList, geoLocList, langList,
              browsersList, operatingSysList, moboileCarriersList,
              devicesList, priceModel, price, maxDailyBudget, alltimeList,
              keywordsList, impressionsEnabled, impressions, minutes,
              )

    # 更新广告材料
    if type.find('PUT') >= 0:
        adJson = JsonUtils.getPutJson(adName, adStyle, publisher_ad_types, cateList, geoLocList, langList,
                                       browsersList, operatingSysList, moboileCarriersList,
                                       devicesList, priceModel, price, maxDailyBudget, alltimeList,
                                       keywordsList, impressionsEnabled, impressions, minutes,
                                       )

    print(json.dumps(adJson, ensure_ascii=False))
    return adJson


# 生成上传广告材料的json格式
def getVariation(fileId, adName, keywords, adSite):
    # varJson = {
    #     'name': adName,
    #     'description': keywords,
    #     'url': adSite,
    #     'id_library_file': fileId
    # }
    # 此格式是postman生成，待优化
    varJson = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; " \
              "name=\"name\"\r\n\r\n"+adName+"\r\n" \
              "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; " \
              "name=\"description\"\r\n\r\n"+keywords+"\r\n" \
              "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; " \
              "name=\"id_library_file\"\r\n\r\n"+str(fileId)+"\r\n" \
              "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; " \
              "name=\"url\"\r\n\r\n"+str(adSite)+"\r\n" \
              "------WebKitFormBoundary7MA4YWxkTrZu0gW--"
    print(varJson)
    return varJson
    pass

# 生成上传广告材料的json格式
def get_variation_without_pic(adSite):
    # varJson = {
    #     'name': adName,
    #     'description': keywords,
    #     'url': adSite,
    #     'id_library_file': fileId
    # }
    # 此格式是postman生成，待优化
    varJson = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; " \
              "name=\"url\"\r\n\r\n"+str(adSite)+"\r\n" \
              "------WebKitFormBoundary7MA4YWxkTrZu0gW--"
    print(varJson)
    return varJson
    pass




